var amapFile = require('../../utils/amap-wx.js');
//index.js
//获取应用实例
var app = getApp()

Page({
  data: {
    fileServerPath: app.globalData.fileServerPath,
    goodsList: [],
    isNeedLogistics: 0, // 是否需要物流信息
    allGoodsPrice: 0,
    yunPrice: 1,
    allGoodsAndYunPrice: 0,
    goodsJsonStr: "",
    orderType: wx.getStorageSync('orderType'), //订单类型，购物车下单或立即支付下单，默认是购物车，
    hasNoCoupons: true,
    coupons: [],
    youhuijine: 0, //优惠券金额
    curCoupon: null, // 当前选择使用的优惠券
    canBuy: false,
    to_pois: ""
  },

  onShow: function () {
    var that = this;
    var shopCarInfo = wx.getStorageSync('shopCarInfo');
    if (shopCarInfo.length === 0) {
      wx.reLaunch({
        url: "/pages/shop-cart/index"
      })
    } else {

      var gprice = 0;
      for (var i = 0; i < shopCarInfo.length; i++) {
        gprice += shopCarInfo[i].goods_price * shopCarInfo[i].goods_number
      }
      that.setData({
        goodsList: shopCarInfo,
        allGoodsPrice: gprice.toFixed(2)
      });
      that.initShippingAddress();
    }

  },

  onLoad: function (e) {
    var that = this;
    //显示收货地址标识
    that.setData({
      isNeedLogistics: 1,
    });
  },

  //创建订单
  createOrder: function (e) {
    var that = this;
    console.log(wx.getStorageSync('orderType'))
    if (that.data.canBuy) {
      if (wx.getStorageSync('orderType') === "buyNow") {
        var goodsList = this.data.goodsList;
        var postscript = e.detail.value.remark; // 备注信息
        var goods_id = "", goods_attr = "", goods_attr_id = "", goods_number = "",
          goods_img = "", goods_name = "";
        for (var i = 0; i < goodsList.length; i++) {
          if (i === 0) {
            goods_id += goodsList[i].goods_id;
            goods_name += goodsList[i].goods_name;
            goods_attr += goodsList[i].goods_attr.replace(",", "\|");
            goods_attr_id += goodsList[i].goods_attrs_id.replace(",", "\|");
            goods_number += goodsList[i].goods_number;
            goods_img += goodsList[i].goods_img;
          } else {
            goods_id = goods_id + "," + goodsList[i].goods_id;
            goods_name = goods_name + "," + goodsList[i].goods_name;
            goods_attr = goods_attr + "," + goodsList[i].goods_attr.replace(",", "\|");
            goods_attr_id = goods_attr_id + "," + goodsList[i].goods_attrs_id.replace(",", "\|");
            goods_number = goods_number + "," + goodsList[i].goods_number;
            goods_img = goods_img + "," + goodsList[i].goods_img;
          }
        }
        var postData = {
          token: wx.getStorageSync("token"),
          goods_id: goods_id,//goods_id ,分割
          goods_name: goods_name,//goods_name ,分割
          goods_attr: goods_attr,// 商品参数 同一商品参数|分割 不同,
          goods_attr_id: goods_attr_id,//商品参数 同一商品参数|分割 不同,
          goods_number: goods_number,//商品数量,分割
          goods_img: goods_img,//商品图片,分割
          postscript: postscript,//买家留言
          freight_id: 1,
          name: that.data.curAddressData.name, //用户姓名
          user_location: that.data.to_pois,//用户位置
          province: that.data.curAddressData.province,//省
          city: that.data.curAddressData.city,//市
          district: that.data.curAddressData.district,//区
          street: that.data.curAddressData.street,//街道
          address: that.data.curAddressData.address,//地址
          zipcode: that.data.curAddressData.code,//邮编
          phone: that.data.curAddressData.phone,//电话

        };
        console.log(postData)
        wx.request({
          url: app.globalData.rootPath + '/m/order',
          method: 'POST',
          header: {
            'content-type': 'application/x-www-form-urlencoded'
          },
          data: postData, // 设置请求的 参数
          success: (res) => {
            if (res.data.meta.code === 200) {
              wx.removeStorageSync('shopCarInfo');
              wx.requestPayment({
                'timeStamp': res.data.data.timeStamp,
                'nonceStr': res.data.data.nonceStr,
                'package': res.data.data.package1,
                'signType': 'MD5',
                'paySign': res.data.data.paySign,
                fail: function (aaa) {
                  if (aaa.errMsg == "requestPayment:fail cancel") {
                    wx.showModal({
                      title: '提示',
                      content: "支付已取消，您可以在30分钟内完成支付。",
                      showCancel: false
                    })
                  } else {
                    wx.showModal({
                      title: '提示',
                      content: aaa.errMsg,
                      showCancel: false
                    })
                  }

                  wx.navigateTo({
                    url: "/pages/order-list/index"
                  });
                },
                success: function (res) {
                  wx.navigateTo({
                    url: "/pages/order-list/index"
                  });
                }
              })
            } else {
              wx.showModal({
                title: '提示',
                content: res.data.meta.message,
                showCancel: false
              })
            }
          }
        })
      }
      if (wx.getStorageSync('orderType') === "shopCar") {
        var goodsList = this.data.goodsList;
        var postscript = e.detail.value.remark; // 备注信息
        var goods_id = "", goods_attr = "", goods_attr_id = "", goods_number = "",
          goods_img = "", goods_name = "", cart_id = "";
        for (var i = 0; i < goodsList.length; i++) {
          if (i === 0) {
            cart_id += goodsList[i].id;
            goods_id += goodsList[i].goods_id;
            goods_name += goodsList[i].goods_name;
            goods_attr += goodsList[i].goods_attr.replace(",", "\|");
            goods_attr_id += goodsList[i].goods_attrs_id.replace(",", "\|");
            goods_number += goodsList[i].goods_number;
            goods_img += goodsList[i].goods_img;
          } else {
            cart_id = cart_id + "," + goodsList[i].id;
            goods_id = goods_id + "," + goodsList[i].goods_id;
            goods_name = goods_name + "," + goodsList[i].goods_name;
            goods_attr = goods_attr + "," + goodsList[i].goods_attr.replace(",", "\|");
            goods_attr_id = goods_attr_id + "," + goodsList[i].goods_attrs_id.replace(",", "\|");
            goods_number = goods_number + "," + goodsList[i].goods_number;
            goods_img = goods_img + "," + goodsList[i].goods_img;
          }
        }
        var postData = {
          token: wx.getStorageSync("token"),
          cart_id: cart_id,
          goods_id: goods_id,//goods_id ,分割
          goods_name: goods_name,//goods_name ,分割
          goods_attr: goods_attr,// 商品参数 同一商品参数|分割 不同,
          goods_attr_id: goods_attr_id,//商品参数 同一商品参数|分割 不同,
          goods_number: goods_number,//商品数量,分割
          goods_img: goods_img,//商品图片,分割
          postscript: postscript,//买家留言
          freight_id: 1,
          name: that.data.curAddressData.name, //用户姓名
          user_location: that.data.to_pois,//用户位置
          province: that.data.curAddressData.province,//省
          city: that.data.curAddressData.city,//市
          district: that.data.curAddressData.district,//区
          street: that.data.curAddressData.street,//街道
          address: that.data.curAddressData.address,//地址
          zipcode: that.data.curAddressData.code,//邮编
          phone: that.data.curAddressData.phone,//电话

        };
        console.log(postData)
        wx.request({
          url: app.globalData.rootPath + '/m/order',
          method: 'POST',
          header: {
            'content-type': 'application/x-www-form-urlencoded'
          },
          data: postData, // 设置请求的 参数
          success: (res) => {
            if (res.data.meta.code === 200) {
              wx.removeStorageSync('shopCarInfo');
              wx.requestPayment({
                'timeStamp': res.data.data.timeStamp,
                'nonceStr': res.data.data.nonceStr,
                'package': res.data.data.package1,
                'signType': 'MD5',
                'paySign': res.data.data.paySign,
                fail: function (aaa) {
                  if (aaa.errMsg == "requestPayment:fail cancel") {
                    wx.showModal({
                      title: '提示',
                      content: "支付已取消，您可以在30分钟内完成支付。",
                      showCancel: false
                    })
                  } else {
                    wx.showModal({
                      title: '提示',
                      content: aaa.errMsg,
                      showCancel: false
                    })
                  }

                  wx.navigateTo({
                    url: "/pages/order-list/index"
                  });
                },
                success: function (res) {
                  wx.navigateTo({
                    url: "/pages/order-list/index"
                  });
                }
              })
            } else {
              wx.showModal({
                title: '提示',
                content: res.data.meta.message,
                showCancel: false
              })
            }
          }
        })
      }
    } else {
      wx.showModal({
        title: '提示',
        content: '提交失败',
        showCancel: false
      })
    }
  },

  //获取默认收货地址
  initShippingAddress: function () {
    var that = this;
    wx.request({
      url: app.globalData.rootPath + "/m/address/default",
      data: {
        token: wx.getStorageSync("token")
      },
      success: (res) => {
        if (res.data.meta.code === 200 && res.data.data) {
          that.setData({
            curAddressData: res.data.data,
            canBuy:true
          });

        } else {
          wx.showModal({
            title: '提示',
            content: '请检查您的收货地址',
            showCancel: false
          })
          that.setData({
            curAddressData: null
          });
        }
      }
    })
  },

  addAddress: function () {
    wx.navigateTo({
      url: "/pages/address-add/index"
    })
  },
  change_selectAddress: function () {
    wx.navigateTo({
      url: "/pages/select-address/index"
    })
  },
  add_selectAddress: function () {
    wx.navigateTo({
      url: "/pages/select-address/index"
    })
  },

})
